package com.heima.wemedia.service.impl;

import com.heima.api.ScheduleFeignClient;
import com.heima.model.common.enums.TaskTypeEnum;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.utils.common.ProtostuffUtil;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsTaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author DiXiaoNie
 * @since 2022/12/25 11:48
 */
@Service
@Slf4j
public class WmNewsTaskServiceImpl implements WmNewsTaskService {
    @Resource
    private ScheduleFeignClient scheduleFeignClient;

    @Resource
    private WmNewsAutoScanService wmNewsAutoScanService;

    /**
     * 浏览新闻任务
     *
     * @author DiXiaoNie
     * @date 2022/12/25
     * @Scheduled(fixedRate = 50000)  定时任务 每五秒钟拉取一次
     */
    @Override
    @Scheduled(fixedRate = 50000)
    public void scanNewsByTask() {
        log.info("文章审核---消费任务执行---begin---");
        //1.远程调用feign消费任务接口
        Integer type = TaskTypeEnum.NEWS_SCAN_TIME.getTaskType();
        Integer priority = TaskTypeEnum.NEWS_SCAN_TIME.getPriority();
        Task task = this.scheduleFeignClient.pullTask(type, priority);
        //3.获取wmNewsId

        if (task != null && task.getParameters().length > 0) {
            byte[] parameters = task.getParameters();
            WmNews wmNews = ProtostuffUtil.deserialize(parameters, WmNews.class);

            //2.调用自动审核业务接口
            this.wmNewsAutoScanService.autoScanWmNews(wmNews.getId());
            log.info("文章审核---消费任务执行---end---");
        }

    }

    /**
     * 将消息添加到任务
     *
     * @param id          id
     * @param publishTime 发布时间
     * @author DiXiaoNie
     * @date 2022/12/25
     */
    @Override
    @Async
    public void addNewsToTask(Integer id, Date publishTime) {
        Task task = new Task();
        //类型
        task.setTaskType(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType());
        task.setPriority(TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        task.setExecuteTime(publishTime.getTime());
        //参数至少包含文章id
        WmNews wmNews = new WmNews();
        wmNews.setId(id);

        byte[] parames = ProtostuffUtil.serialize(wmNews);
        task.setParameters(parames);

        //1.调用feign接口
        scheduleFeignClient.addTask(task);
    }
}
